from collections import OrderedDict
import time
import datetime

from flask import jsonify, Blueprint
from flask import request
from flask_jwt import jwt_required

from db import *

record_day = Blueprint("record_day", __name__)


@record_day.route('/record_days')
@jwt_required()
def search_content():
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    symbol = request.args.get('symbol')
    concept = request.args.get('concept')
    name = request.args.get('name')

    start_ts = 0
    end_ts = 0
    if end_date and start_date:
        start_ts = int(time.mktime(time.strptime(start_date, '%Y-%m-%d')))
        end_ts = int(time.mktime(time.strptime(
            end_date, '%Y-%m-%d'))) + 24 * 3600
        if end_ts - start_ts > 5 * 24 * 3600:
            return jsonify({})

    ret = search_record(start_ts, end_ts, symbol, concept, name)
    response = jsonify({"data": ret})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response


def search_record(start_ts, end_ts, symbol, concept, name, ddb=1):
    tpdb = record_main_db
    if ddb == 0:
        tpdb = record_yes_main_db
    elif ddb == 2:
        tpdb = record_yes_db
    if not start_ts and not end_ts:
        # tpdb = record_tmp_db
        start_ts = int(time.mktime(datetime.date.today().timetuple()))
        end_ts = start_ts + 24 * 3600

    query_filter = {"ts": {"$gte": start_ts, "$lt": end_ts}}

    if concept:
        symbols = stock_db.find(
            {'use': 1, "ths_hxtc": {"$regex": f".*{concept}.*"}})
        symbols = [s['symbol'] for s in symbols]
        query_filter["symbol"] = {"$in": symbols}
    else:
        if name:
            name = stock_db.find_one({'use': 1, "name": name})
            query_filter["symbol"] = name['symbol'] if name else ''
            query_filter.pop('ts')
        if symbol:
            query_filter["symbol"] = symbol
            query_filter.pop('ts')


    records = tpdb.find(query_filter).sort(
        [('update_time', -1), ('symbol', 1)])

    r = []
    for k in records:
        h = {}
        stocks = stock_db.find_one({"symbol": k['symbol']})
        days = record_day_db.find({"symbol": k['symbol']}).sort([('date', -1)])
        h['ts'] = k['ts']
        h['symbol'] = k['symbol']
        h['name'] = stocks['name']
        h['hxtc'] = stocks.get('ths_hxtc', stocks.get('hxtc', ''))
        h['high'] = k.get('high', -2)
        h['macd'] = k.get('macd', -3)
        # print(k['sons'])
        h['time'] = ' '.join([time.strftime('%H:%M', time.localtime(
            i['ts'])) for i in k['sons'] if i.get('ts')])
        
        h['price'] = k['sons'][0].get("price", 0)
        h['range'] = round((h['price'] - stocks['end_price'] ) / stocks['end_price'] * 100, 2) if h['price'] else -20
        h['increase'] = round((stocks['end_price'] - h['price']) / h['price'] * 100, 2) if h['price'] else -20
        h['date'] = ' '.join([i['date'] for i in days])
        h['url'] = f"https://wap.eastmoney.com/quote/stock/{k['symbol'].replace('SH', '1.').replace('SZ', '0.')}.html"
        r.append(h)
    return r


@record_day.route('/post_collect_record', methods=['post'])
@jwt_required()
def post_collect_record():
    data = request.get_json()['data']
    ts = time.time()
    data['col_ts'] = int(ts)
    data['delete'] = 0
    record_collect_db.update_one({'symbol': data['symbol']}, {
                                 "$set": data}, upsert=True)

    response = jsonify({"data": 'OK'})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response

@record_day.route('/delete_record', methods=['post'])
@jwt_required()
def delete_record():
    data = request.get_json()['data']
    symbol = data['symbol']
    ts = data['ts']
    record_main_db.delete_one({'symbol': symbol, 'ts': ts})
    response = jsonify({"data": "OK"})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response

@record_day.route('/get_collect_records', methods=['get'])
@jwt_required()
def get_collect_record():
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    symbol = request.args.get('symbol')
    concept = request.args.get('concept')
    name = request.args.get('name')

    start_ts = 0
    end_ts = 0
    if end_date and start_date:
        start_ts = int(time.mktime(time.strptime(start_date, '%Y-%m-%d')))
        end_ts = int(time.mktime(time.strptime(
            end_date, '%Y-%m-%d'))) + 24 * 3600
        if end_ts - start_ts > 5 * 24 * 3600:
            return jsonify({})

    ret = search_col_record(start_ts, end_ts, symbol, concept, name)
    response = jsonify({"data": ret})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response


def search_col_record(start_ts, end_ts, symbol, concept, name):
    query_filter = {'delete': 0}
    if start_ts and not end_ts:
        query_filter["ts"] = {"$gte": start_ts, "$lte": end_ts}

    if concept:
        symbols = stock_db.find(
            {'use': 1, "ths_hxtc": {"$regex": f".*{concept}.*"}})
        symbols = [s['symbol'] for s in symbols]
        query_filter["symbol"] = {"$in": symbols}
    else:
        if name:
            name = stock_db.find_one({'use': 1, "name": name})
            query_filter["symbol"] = name['symbol'] if name else ''
        if symbol:
            query_filter["symbol"] = symbol
    all = record_collect_db.find(query_filter).sort(
        [('col_ts', -1), ('symbol', 1)])
    a = []
    for i in all:
        i.pop('_id')
        i['col_ts'] = time.strftime('%Y-%m-%d', time.localtime(i['col_ts']))
        a.append(i)
    return a


@record_day.route('/del_collect_records', methods=['delete'])
@jwt_required()
def del_collect_record():
    symbol = request.args.get('symbol')
    record_collect_db.update_one(
        {'symbol': symbol}, {"$set": {'delete': 1}}, upsert=True)
    response = jsonify({"data": "OK"})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response


@record_day.route('/record_yes_days')
@jwt_required()
def search_yes_content():
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    symbol = request.args.get('symbol')
    concept = request.args.get('concept')
    name = request.args.get('name')

    start_ts = 0
    end_ts = 0
    if end_date and start_date:
        start_ts = int(time.mktime(time.strptime(start_date, '%Y-%m-%d')))
        end_ts = int(time.mktime(time.strptime(
            end_date, '%Y-%m-%d'))) + 24 * 3600
        if end_ts - start_ts > 5 * 24 * 3600:
            return jsonify({})

    ret = search_record(start_ts, end_ts, symbol, concept, name, ddb=0)
    response = jsonify({"data": ret})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response


@record_day.route('/record_east_days')
@jwt_required()
def search_east_content():
    start_date = request.args.get('startDate')
    end_date = request.args.get('endDate')
    symbol = request.args.get('symbol')
    concept = request.args.get('concept')
    name = request.args.get('name')

    start_ts = 0
    end_ts = 0
    if end_date and start_date:
        start_ts = int(time.mktime(time.strptime(start_date, '%Y-%m-%d')))
        end_ts = int(time.mktime(time.strptime(
            end_date, '%Y-%m-%d'))) + 24 * 3600
        if end_ts - start_ts > 5 * 24 * 3600:
            return jsonify({})

    ret = search_record(start_ts, end_ts, symbol, concept, name, ddb=2)
    response = jsonify({"data": ret})
    response.headers["Content-Type"] = "application/json; charset=utf-8"
    return response
